﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TheHeGeoDao
{
    public class DaoHelper
    {
        protected static TheheGeoDbEntities PrtEntities;
        protected static string SqlStr;
        public static TheheGeoDbEntities Entities
        {
            get
            {
                try
                {
                    
                    if (PrtEntities == null)
                    {
                        PrtEntities = new TheheGeoDbEntities();
                        Entities.Database.CommandTimeout = 180;
                    }
                    else if (PrtEntities.Database.Connection.State != ConnectionState.Open)
                    {
                        PrtEntities.Database.Connection.Open();
                    }
                    return PrtEntities;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            set { PrtEntities = value; }
        }
        
        public static TheheGeoDbEntities ReOpen()
        {
            PrtEntities = new TheheGeoDbEntities();
            Entities.Database.CommandTimeout = 180;
            return PrtEntities;
        }

        public static string SqlConnectionString
        {
            get { return SqlStr; }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    SqlStr = value;
                    if (PrtEntities.Database.Connection.State==ConnectionState.Open)
                        PrtEntities.Database.Connection.Close();
                    PrtEntities = new TheheGeoDbEntities();
                    PrtEntities.Database.Connection.ConnectionString = SqlStr;
                    PrtEntities.Database.Connection.Open();
                }
            }
        }

        public static void Exit()
        {
            if (PrtEntities != null)
            {
                PrtEntities.Database.Connection.Close();
                PrtEntities.Dispose();
            }
        }

        public static bool TestConnectionStr(string str)
        {
            try
            {
                var ent = new TheheGeoDbEntities();
                ent.Database.Connection.ConnectionString = str;
                ent.Database.Connection.Open();
                bool rs = (ent.Database.Connection.State == ConnectionState.Open);
                ent.Database.Connection.Close();
                return rs;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
